<template>
  <el-popover
    placement="bottom-start"
    trigger="click"
    popper-class="customPopper"
    :visible.sync="popoverVisible"
    ref="popover"
  >
    <template #reference>
      <p
        :class="isActive ? 'active' : ''"
        class="text-[#fff] text-xl font-bold flex justify-start items-center cursor-pointer buyPlain"
        @click="
          () => {
            popoverVisible = !popoverVisible;
            if (popoverVisible) {
              isActive = true;
            } else {
              isActive = false;
            }
          }
        "
      >
        <img
          src="@/assets/images/home/Flight.png"
          width="20"
          height="20"
          alt=""
          class="mr-2"
        />
        {{ $t("home.Flight") }}
      </p>
    </template>
    <div class="bg-[#fff] w-[220px] h-[30px] radioGroup">
      <el-radio-group v-model="formInline.tripType">
        <el-radio :value="1">{{ $t("home.oneWay") }}</el-radio>
        <div class="divider"></div>
        <el-radio :value="2">{{ $t("home.roundTrip") }}</el-radio>
      </el-radio-group>
    </div>
    <div
      class="bg-[#fff] formContent flex justify-start items-center"
      style="flex: 1"
    >
      <div class="flex justify-between items-center">
        <el-popover
          placement="bottom-start"
          popper-class="fromPopover"
          :width="500"
          trigger="click"
          :visible.sync="fromCityVisible"
          @close="closePopover"
        >
          <template #reference>
            <div
              class="flex flex-col justify-start items-start px-4 customInput"
            >
              <img
                src="@/assets/images/home/Leaving.png"
                width="24"
                height="22"
                alt=""
              />
              <el-input
                v-model="formInline.fromCity"
                :placeholder="$t('home.leavingFrom')"
                style="width: 100%"
                size="large"
                @click="
                  () => ((fromCityVisible = true), (toCityVisible = false))
                "
                @input="searchFromCity"
              >
              </el-input>
            </div>
          </template>
          <div class="bg-[#f7f7fb] rounded-lg" v-if="isShowAerodrome">
            <div v-for="item of airportList" :key="item.cityCode">
              <h2 class="px-2 py-1">
                <el-tag class="mr-2">{{ $t("home.city") }}</el-tag
                >{{ item.cityName }} ({{ $t("home.allAirport") }})
              </h2>
              <ul
                class="flex flex-col justify-start flex-wrap items-start bg-[#fff] py-4 px-2 pl-10"
              >
                <li
                  v-for="airport of item.airportList"
                  :key="airport.airportCode"
                  class="cursor-pointer h-[30px]"
                  @click="selectFromCity(airport, true)"
                >
                  <el-tag class="mr-2" type="warning">{{
                    $t("home.airport")
                  }}</el-tag
                  >{{ airport.airportName }}
                </li>
              </ul>
            </div>
          </div>
          <div class="bg-[#f7f7fb] rounded-lg" v-else>
            <div v-for="item of hotCity" :key="item.id">
              <h2 class="px-2 py-1">{{ item.groupName }}</h2>
              <ul
                class="flex justify-start flex-wrap items-center bg-[#fff] py-4 px-2 cityList"
              >
                <li
                  v-for="city of item.cityList"
                  :key="city.cityCode"
                  class="cursor-pointer"
                  @click="selectFromCity(city, false)"
                >
                  {{ city.cityName }}
                </li>
              </ul>
            </div>
          </div>
        </el-popover>
        <img
          src="@/assets/images/home/switch.png"
          alt=""
          width="24"
          class="mr-4 cursor-pointer"
          @click="switchInput"
        />
      </div>
      <div class="flex justify-between items-center">
        <div class="flex flex-col justify-start items-start px-4 customInput">
          <img
            src="@/assets/images/home/Goingto.png"
            width="24"
            height="20"
            alt=""
          />
          <el-popover
            placement="bottom-start"
            popper-class="toPopover"
            :width="500"
            trigger="click"
            :visible.sync="toCityVisible"
            @close="closePopover"
          >
            <template #reference>
              <el-input
                v-model="formInline.toCity"
                :placeholder="$t('home.goingTo')"
                style="width: 100%"
                size="large"
                @click="
                  () => ((toCityVisible = true), (fromCityVisible = false))
                "
                @input="searchToCity"
              >
              </el-input>
            </template>
            <div class="bg-[#f7f7fb]" v-if="isShowAerodromeTo">
              <div v-for="item of airportList" :key="item.cityCode">
                <h2 class="px-2 py-1">
                  <el-tag class="mr-2">{{ $t("home.city") }}</el-tag>
                  {{ item.cityName }} ({{ $t("home.allAirport") }})
                </h2>
                <ul
                  class="flex flex-col justify-start flex-wrap items-start bg-[#fff] py-4 px-2 pl-10"
                >
                  <li
                    v-for="airport of item.airportList"
                    :key="airport.airportCode"
                    class="cursor-pointer h-[30px]"
                    @click="selectToCity(airport, true)"
                  >
                    <el-tag class="mr-2" type="warning">{{
                      $t("home.airport")
                    }}</el-tag
                    >{{ airport.airportName }}
                  </li>
                </ul>
              </div>
            </div>
            <div class="bg-[#f7f7fb]" v-else>
              <div v-for="item of hotCity" :key="item.id">
                <h2 class="px-2 py-1">{{ item.groupName }}</h2>
                <ul
                  class="flex justify-start flex-wrap items-center bg-[#fff] py-4 px-2 cityList"
                >
                  <li
                    v-for="city of item.cityList"
                    :key="city.cityCode"
                    class="cursor-pointer"
                    @click="selectToCity(city, false)"
                  >
                    {{ city.cityName }}
                  </li>
                </ul>
              </div>
            </div>
          </el-popover>
        </div>
      </div>
      <div class="flex justify-between items-center">
        <div class="flex flex-col justify-start items-start px-4 customInput">
          <img
            src="@/assets/images/home/AnyDate.png"
            width="20"
            height="20"
            alt=""
          />
          <el-date-picker
            style="width: 100%"
            v-model="formInline.fromDate"
            type="date"
            :placeholder="$t('home.departingOn')"
            prefix-icon=""
            class="no-icon"
            :disabled-date="disabledDate"
            @focus="closePopover()"
          />
        </div>
      </div>
      <div
        class="flex justify-between items-center"
        v-if="formInline.tripType == 2"
      >
        <div class="flex flex-col justify-start items-start px-4 customInput">
          <img
            src="@/assets/images/home/AnyDate.png"
            width="20"
            height="20"
            alt=""
          />
          <el-date-picker
            style="width: 100%"
            v-model="formInline.retDate"
            type="date"
            :placeholder="$t('home.departingOn')"
            prefix-icon=""
            class="no-icon"
            :disabled-date="disabledDate1"
            @focus="closePopover()"
          />
        </div>
      </div>
      <div
        class="flex justify-center items-start"
        style="flex: 1; height: 50px"
      >
        <div
          class="flex flex-col justify-center items-start px-6 customInput pl-4"
        >
          <img
            src="@/assets/images/home/Adult.png"
            width="15"
            height="15"
            alt=""
          />
          <el-popover
            placement="bottom-start"
            width="260"
            trigger="click"
            popper-class="inputPopper"
            :visible.sync="popoverVisible1"
            @close="popoverVisible1 = false"
            ref="inputPopper"
          >
            <template #reference>
              <p
                class="flex justify-start items-center cursor-pointer"
                @click="(popoverVisible1 = !popoverVisible1), closePopover()"
                style="margin-top: 3px"
              >
                <span class="mr-2 text-[#4a4a4a]">{{ adults }}</span>
                <img
                  src="@/assets/images/home/drop-down.png"
                  alt=""
                  width="14"
                />
              </p>
            </template>
            <div class="user flex flex-col justify-center p-2">
              <p class="text-sm font-bold mb-4">
                {{ $t("home.selectTip") }}
              </p>
              <ul>
                <li class="flex justify-between items-center mb-4">
                  <p class="flex justify-start items-center">
                    <img
                      src="@/assets/images/home/grownMan.png"
                      width="10"
                      height="10"
                      class="mr-2"
                      alt=""
                    />
                    {{ $t("home.grownMan") }}
                  </p>
                  <p class="flex justify-start items-center">
                    <el-icon
                      class="sub"
                      @click="subUser('user')"
                      :class="{
                        'is-disabled':
                          formInline.grownMan <= 1 ||
                          formInline.grownMan <= formInline.infant,
                      }"
                      ><Remove
                    /></el-icon>
                    <el-input
                      class="mr-1 ml-1 customInputValue"
                      v-model="formInline.grownMan"
                    />
                    <el-icon
                      class="add"
                      @click="addUser('user')"
                      :class="{ 'is-disabled': grownManDisabled }"
                      ><CirclePlus
                    /></el-icon>
                  </p>
                </li>
                <li class="flex justify-between items-center mb-4">
                  <div class="flex justify-start flex-col">
                    <p class="flex justify-start items-center mb-2">
                      <img
                        src="@/assets/images/home/children.png"
                        width="10"
                        height="10"
                        class="mr-2"
                        alt=""
                      />
                      {{ $t("home.children") }}
                    </p>
                    <p>{{ $t("home.childrenTip") }}</p>
                  </div>
                  <p class="flex justify-start items-center">
                    <el-icon
                      class="sub"
                      @click="subUser('children')"
                      :class="{ 'is-disabled': formInline.children <= 0 }"
                      ><Remove
                    /></el-icon>
                    <el-input
                      class="mr-1 ml-1 customInputValue"
                      v-model="formInline.children"
                    />
                    <el-icon
                      class="add"
                      @click="addUser('children')"
                      :class="{ 'is-disabled': childrenDisabled }"
                      ><CirclePlus
                    /></el-icon>
                  </p>
                </li>
                <li class="flex justify-between items-center mb-4">
                  <div class="flex flex-col justify-start">
                    <p class="flex justify-start items-center mb-2">
                      <img
                        src="@/assets/images/home/infant.png"
                        width="10"
                        height="10"
                        class="mr-2"
                        alt=""
                      />
                      {{ $t("home.infants") }}
                    </p>
                    <p>{{ $t("home.infantsTip") }}</p>
                  </div>
                  <p class="flex justify-start items-center">
                    <el-icon
                      class="sub"
                      @click="subUser('infant')"
                      :class="{ 'is-disabled': formInline.infant <= 0 }"
                      ><Remove
                    /></el-icon>
                    <el-input
                      class="mr-1 ml-1 customInputValue"
                      v-model="formInline.infant"
                    />
                    <el-icon
                      class="add"
                      @click="addUser('infant')"
                      :class="{ 'is-disabled': infantDisabled }"
                      ><CirclePlus
                    /></el-icon>
                  </p>
                </li>
                <li
                  class="flex justify-end items-end text-[#0373c1] cursor-pointer"
                  @click="submitAdult"
                >
                  {{ $t("home.submit") }}
                </li>
              </ul>
            </div>
          </el-popover>
        </div>
      </div>
      <div class="flex justify-between items-center">
        <div class="flex flex-col justify-start items-start px-4 customInput">
          <img
            src="@/assets/images/home/Economy.png"
            width="15"
            height="15"
            alt=""
          />
          <el-select
            v-model="formInline.cabinGrades"
            :placeholder="$t('home.Economy')"
            style="width: 80%"
            size="large"
            @focus="closePopover()"
          >
            <el-option-group
              v-for="group in options"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-option-group>
          </el-select>
        </div>
      </div>
      <div class="findPlain" @click="findPlain">
        {{ $t("home.findTicket") }}
      </div>
    </div>
  </el-popover>
</template>
<script setup>
import { onMounted, onUnmounted, ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import { findPlainApi, findCity } from "@/api/index";
import { CirclePlus, Remove } from "@element-plus/icons-vue";

import { dayjs } from "element-plus";
import { formatDate } from "@/utils/common";
const { t } = useI18n();

const formInline = ref({
  tripType: 1,
  grownMan: 1,
  children: 0,
  infant: 0,
});

const disabledDate = (time) => {
  return dayjs(time).isBefore(dayjs().startOf("day"), "day");
};

const disabledDate1 = (date) => {
  // 获取今天的日期
  const today = new Date(formInline.value.fromDate);
  // 如果日期在今天之前，则禁用
  return date < today;
};

const toCityVisible = ref(false);
const fromCityVisible = ref(false);
const isShowAerodrome = ref(false);
const isShowAerodromeTo = ref(false);
const airportList = ref([]);

const adults = computed(() => {
  let grownMan = "";
  if (formInline.value.grownMan > 0) {
    grownMan = formInline.value.grownMan + t("home.grownMan");
  } else {
    grownMan = "";
  }
  let children = "";
  if (formInline.value.children > 0) {
    children = formInline.value.children + t("home.children");
  } else {
    children = "";
  }
  let infant = "";
  if (formInline.value.infant > 0) {
    infant = formInline.value.infant + t("home.infant");
  } else {
    infant = "";
  }
  return grownMan + " " + children + " " + infant;
});

const hotCity = computed(() => {
  return [
    {
      groupName: t("home.Asia"),
      groupCode: "2",
      type: 1,
      cityList: [
        {
          cityCode: "KUL",
          cityName: t("home.KualaLumpur"),
        },
        {
          cityCode: "TPE",
          cityName: t("home.Taipei"),
        },
        {
          cityCode: "BLR",
          cityName: t("home.Bengaluru"),
        },
        {
          cityCode: "TYO",
          cityName: t("home.Tokyo"),
        },
        {
          cityCode: "SEL",
          cityName: t("home.Seoul"),
        },
      ],
    },
    {
      groupName: t("home.Europe"),
      groupCode: "5",
      type: 1,
      cityList: [
        {
          cityCode: "PAR",
          cityName: t("home.Paris"),
        },
        {
          cityCode: "LON",
          cityName: t("home.London"),
        },
        {
          cityCode: "ROM",
          cityName: t("home.Rome"),
        },
        {
          cityCode: "HAM",
          cityName: t("home.Hamburg"),
        },
        {
          cityCode: "MUC",
          cityName: t("home.Munich"),
        },
      ],
    },
    {
      groupName: t("home.NorthAmerica"),
      groupCode: "7",
      type: 1,
      cityList: [
        {
          cityCode: "CHI",
          cityName: t("home.Chicago"),
        },
        {
          cityCode: "NYC",
          cityName: t("home.NewYork"),
        },
        {
          cityCode: "YOW",
          cityName: t("home.Ottawa"),
        },
        {
          cityCode: "DFW",
          cityName: t("home.Dallas"),
        },
        {
          cityCode: "SFO",
          cityName: t("home.SanFrancisco"),
        },
        {
          cityCode: "LAX",
          cityName: t("home.LosAngeles"),
        },
      ],
    },
  ];
});

const selectFromCity = (item, isAirport) => {
  if (isAirport) {
    formInline.value.fromCity = item.airportName;
    formInline.value.fromCityCode = item.airportCode;
    fromCityVisible.value = false;
    toCityVisible.value = false;
  } else {
    formInline.value.fromCity = item.cityName;
    formInline.value.fromCityCode = item.cityCode;
    fromCityVisible.value = false;
    toCityVisible.value = false;
  }
};

const selectToCity = (item, isAirport) => {
  if (isAirport) {
    formInline.value.toCity = item.airportName;
    formInline.value.toCityCode = item.airportCode;
    toCityVisible.value = false;
    fromCityVisible.value = false;
  } else {
    formInline.value.toCity = item.cityName;
    formInline.value.toCityCode = item.cityCode;
    toCityVisible.value = false;
    fromCityVisible.value = false;
  }
};

const searchFromCity = async (val) => {
  if (val) {
    try {
      const res = await findCity({
        keys: val,
        lang: localStorage.getItem("language"),
      });
      airportList.value = res;
      fromCityVisible.value = true;
      isShowAerodrome.value = true;
    } catch {
      isShowAerodrome.value = false;
    }
  } else {
    isShowAerodrome.value = false;
  }
};

const searchToCity = async (val) => {
  if (val) {
    try {
      const res = await findCity({
        keys: val,
        lang: localStorage.getItem("language"),
      });
      airportList.value = res;
      toCityVisible.value = true;
      isShowAerodromeTo.value = true;
    } catch {
      console.log("error");
      isShowAerodromeTo.value = false;
    }
  } else {
    isShowAerodromeTo.value = false;
  }
};

const grownManDisabled = computed(() => {
  if (formInline.value.grownMan + formInline.value.children >= 9) {
    return true;
  }
});

const childrenDisabled = computed(() => {
  if (formInline.value.grownMan + formInline.value.children >= 9) {
    return true;
  }
});

const infantDisabled = computed(() => {
  if (formInline.value.infant >= 4) {
    return true;
  } else if (formInline.value.infant >= formInline.value.grownMan) {
    return true;
  }
});

const submitAdult = () => {
  popoverVisible1.value = false;
};

const options = ref([
  {
    label: `${t("home.EconomyOrPremiumEconomy")}`,
    options: [
      {
        value: "E",
        label: `${t("home.Economy")}`,
      },
      {
        value: "S",
        label: `${t("home.PremiumEconomy")}`,
      },
    ],
  },
  {
    label: `${t("home.BusinessOrFirst")}`,
    options: [
      {
        value: "B",
        label: `${t("home.Business")}`,
      },
      {
        value: "F",
        label: `${t("home.First")}`,
      },
    ],
  },
]);

const switchInput = () => {
  const str = formInline.value.fromCity;
  formInline.value.fromCity = formInline.value.toCity;
  formInline.value.toCity = str;
};

const popoverVisible = ref(true);
const popoverVisible1 = ref(false);
const isActive = ref(true);

const closePopover = () => {
  fromCityVisible.value = false;
  toCityVisible.value = false;
};

const addUser = (val) => {
  if (val === "user" && !grownManDisabled.value) {
    formInline.value.grownMan++;
  } else if (val === "children" && !childrenDisabled.value) {
    formInline.value.children++;
  } else if (val === "infant" && !infantDisabled.value) {
    formInline.value.infant++;
  }
};

const subUser = (val) => {
  if (val === "user") {
    if (formInline.value.grownMan > 1) {
      formInline.value.grownMan--;
    }
  } else if (val === "children") {
    if (formInline.value.children > 0) {
      formInline.value.children--;
    }
  } else if (val === "infant") {
    if (formInline.value.infant > 0) {
      formInline.value.infant--;
    }
  }
};

// 处理点击日期关闭popper
const handleClickOutside = (event) => {
  const fromCity = document.querySelector(".fromPopover");
  const customPopper = document.querySelector(".customPopper");
  if (fromCity && !fromCity.contains(event.target)) {
    if (customPopper && !customPopper.contains(event.target)) {
      closePopover();
    }
  } else {
  }
};

const findPlain = async () => {
  let params = {
    fromCity: formInline.value.fromCityCode,
    toCity: formInline.value.toCityCode,
    fromDate: formInline.value.fromDate
      ? formatDate(formInline.value.fromDate)
      : "",
    adultNum: formInline.value.grownMan,
    childNum: formInline.value.children,
    infantNum: formInline.value.infant,
    cabinGrades: formInline.value.cabinGrades,
    tripType: formInline.value.tripType,
  };
  if (formInline.value.tripType == "2") {
    params.toDate = formatDate(formInline.value.toDate);
  }
  console.log(params, "params");
  try {
    const res = await findPlainApi(params);
    console.log(res, "res");
  } catch {}
};

onMounted(() => {
  // 监听全局点击事件，点击其他区域时关闭 popover
  document.addEventListener("click", handleClickOutside);
});

onUnmounted(() => {
  // 组件销毁时移除全局点击事件监听器
  document.removeEventListener("click", handleClickOutside);
});
</script>
<style lang="scss" scoped>
.radioGroup {
  border-radius: 10px;
  text-align: center;
  position: relative;
  .divider {
    height: 100%;
    width: 1px;
    background-color: #80869f;
    position: absolute;
    left: 50%;
    top: 0;
  }
}
.formContent {
  margin-top: 1px;
  height: 100px;
  z-index: 1111;
  box-shadow: 0 0 4px #ccc;
  div {
    flex: 1;
  }
}
.el-form-item {
  margin-bottom: 0;
}
.el-form-item__label {
  font-size: 16px;
  font-weight: 800;
}
.el-form-item__content {
  display: flex;
  align-items: center;
  background-color: #ccc;
  margin: 10px 0;
}
.customInput {
  border: none;
  background: #fff;
  border-radius: 20px;
  position: relative;
  .endDate {
    position: absolute;
    right: 40%;
    top: 30%;
    color: #a9abb3;
  }
}
.adultInput {
  min-width: 50%;
}
.findPlain {
  width: 100%;
  height: 100%;
  background: #0373c1;
  color: #fff;
  font-size: 16px;
  font-weight: 800;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.userInput {
  .el-input__wrapper.is-focus {
    box-shadow: none !important;
  }
}
.user {
  box-sizing: border-box;
  ul li {
    .el-icon {
      font-size: 20px;
      font-weight: 800;
      cursor: pointer;
    }
    .sub {
      color: #0373c1;
    }
    .add {
      color: #0373c1;
    }
    .is-disabled {
      color: #ccc;
    }
  }
}
.buyPlain {
  width: 150px;
  height: 50px;
  box-sizing: border-box;
}
.active {
  box-sizing: border-box;
  border-bottom: 3px solid #fff;
}
.cityList {
  li {
    width: 30%;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    cursor: pointer;
  }
}
</style>
